﻿using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;

namespace BF
{
    public static class HashUtil
    {
        private static SHA1CryptoServiceProvider sha1Hash;

        private static MD5CryptoServiceProvider md5Hash;

        public static string GetSHA1Hash(string str)
        {
            if (sha1Hash == null)
            {
                sha1Hash = new SHA1CryptoServiceProvider();
            }
            return GetHash(sha1Hash, str);
        }

        public static string GetMD5Hash(string str)
        {
            if (md5Hash == null)
            {
                md5Hash = new MD5CryptoServiceProvider();
            }
            return GetHash(md5Hash, str);
        }

        private static string GetHash(HashAlgorithm algorithm, string str)
        {
            try
            {
                byte[] bytes_in = Encoding.UTF8.GetBytes(str);
                byte[] bytes_out = algorithm.ComputeHash(bytes_in);//计算对象的哈希值

                //由以连字符分隔的十六进制对构成的String，其中每一对表示value 中对应的元素；例如“F-2C-4A”
                string hashStr = BitConverter.ToString(bytes_out);
                //替换-
                hashStr = hashStr.Replace("-", "");
                return hashStr;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[HashUtil] [GetHash] {ex}");
                return "";
            }
        }
    }
}